package com.copa.gameStore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gameStore.client.OrderClient;
import com.copa.gameStore.domain.UserAccount;
import com.copa.gameStore.mapper.UserAccountMapper;
import com.copa.gameStore.service.UserAccountService;
import com.copa.gameStore.vo.OrderLogVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ValidationException;
import java.math.BigDecimal;
import java.util.Optional;

/**
 * @author copa
 * @createDate 2022-09-27 16:11
 * @function
 */
@Service
public class UserAccountServiceImpl implements UserAccountService {

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private OrderClient orderClient;

    @Override
    public void add(UserAccount userAccount) {
        if (userAccountMapper.insert(userAccount) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public void takeAccount(BigDecimal money, UserAccount account) {
        synchronized (account) {
            if (account.getAccount().setScale(2).compareTo(money.setScale(2)) < 0) {
                throw new ValidationException("余额不足~请查看账户余额~");
            }
            account.setAccount(account.getAccount().setScale(2).subtract(money.setScale(2)));
            if (userAccountMapper.updateById(account) <= 0) {
                throw new RuntimeException();
            }
        }
    }

    @Override
    public void recharge(Long userId, BigDecimal money) {
        UserAccount account = Optional.ofNullable(userAccountMapper.selectOne(
                        new QueryWrapper<UserAccount>().eq("user_id", userId)))
                .orElseThrow(() -> new ValidationException("非法操作~"));
        orderClient.rechargeLog(new OrderLogVo()
                .setUserId(userId)
                .setMoney(money.negate())
                .setMessage("您已充值[ " + money + " ]元"));
        takeAccount(money.negate(), account);
    }
}
